<?php
/**
 * @Author: rocky
 * @Copyright: 广州拓冠科技 <http://my8m.com>
 * Date: 2019/8/29
 * Time: 11:50
 */


namespace app\shop\service;


use app\api\service\WechatService;
use app\common\facade\Token;
use app\common\model\Account;
use app\common\model\MemberLevel;
use app\common\model\ShopMember;
use app\common\model\ShopMemberCard;
use app\common\model\ShopCoupon;
use app\common\model\ShopCouponRecord;
use app\common\model\ShopMemberLevel;
use app\common\model\ShopRecharge;
use app\common\model\ShopStore;
use app\common\model\User;
use app\common\model\ShopSchoolRegion;
use app\shop\model\ShopCart;
use app\shop\model\ShopGoods;
use app\shop\model\ShopOrder;
use app\shop\model\ShopOrderGoods;
use app\shop\model\ShopStoreSale;
use library\tools\Data;
use think\Db;
use think\Exception;

class Order
{
    //拼团id
    static $pt_id = 0;
    /**
     * 确认订单
     * @Author: rocky
     * 2019/9/30 17:01
     * @param $post 提交校验数据
     * @return array
     */
    public static function confim($post)
    {
        $msg = false;
        $visable = false;
        $data = [];
        Db::startTrans();
        try {
            switch ($post['type']) {
                // 购物车
                case 1:
                    $carts = ShopCart::uid()->whereIn('id', $post['car_ids'])->with(['goods'])->select();
                    if ($carts->isEmpty()) {
                        $msg = '您的购物车是空的';
                    }
                    //商品标题
                    $title = '';
                    if (count($carts) > 1) {
                        $visable = true;
                    }else{
                        $title = $carts[0]['goods']['title'].$carts[0]['num']."件";
                    }
                    foreach ($carts as $cart) {
                        //判断商品状态
                        if ($cart['goods']['status'] != 1) {
                            $msg = $cart['goods']['title'] . ' - 商品不存在或已下架';
                        }
                        if ($visable){
                            $title .= $cart['goods']['title'].$cart['num'].'件/';
                        }
                        $data['title'] = $title;
                        $data['data'][] = [
                            'good_id' => $cart['goods']['id'],
                            'card_id' => 0,
                            'recharge_id' => 0,
                            'store_id' => $cart['store_id'],
                            'logo' => $cart['goods']['logo'],
                            'title' => $cart['goods']['title'],
                            'price' => $cart['goods']['price'],
                            'vip_price' => $cart['goods']['vip_price'],
                            'num' => $cart['num'],
                        ];
                    }
                    break;
                //充值套餐;
                case 5:
                    $res = ShopRecharge::get($post['recharge_id']);
                    if ($res['status'] != 1) {
                        $msg = '该套餐不存在或已下架';
                    }
                    $data['title'] = '充值-'.$res['money'];
                    $data['data'][] = [
                        'card_id' => 0,
                        'recharge_id' => $post['recharge_id'],
                        'good_id' => 0,
                        'title' => '充值-'.$res['money'],
                        'logo' => '',
                        'price' => $res['pay_money'],
                        'num' => 1,
                    ];
                    break;
                case 6:
                    $res = ShopMemberCard::get($post['card_id']);
                    if ($res['status'] != 1) {
                        $msg = '该会员卡不存在或已下架';
                    }
                    $data['title'] = $res['name'];
                    $data['data'][] = [
                        'card_id' => $post['card_id'],
                        'recharge_id' => 0,
                        'good_id' => 0,
                        'title' => $res['name'],
                        'logo' => '',
                        'price' => $res['money'],
                        'num' => 1,
                    ];
                    break;
            }
            if ($visable){
                $data['title'] = substr($data['title'],0,-1);
            }
            $user_res = User::where('id',Token::id())->find();
            $data['has_subscribe'] = $user_res['is_record']?true:false;
            $is_member = Token::member($post['store_id']);
            $data['is_member'] = $is_member[0]?true:false;
            // $data['laundry_num'] = Token::laundryNum($post['store_id'])?Token::laundryNum($post['store_id']):0;
            $data['laundry_num'] = Token::laundryNum(0)?Token::laundryNum(0):0;
            $data['free_num'] = Token::freeNum($post['store_id'])?Token::freeNum($post['store_id']):0;
            $data['user_money'] = $user_res['money']?$user_res['money']:0;
            // new ShopMemberLevel()
            $user_res['lid'] = 3;
            $discount = ShopMemberLevel::where('id',$user_res['lid'])->find();
            $data['is_discount'] = $discount?true:false;
            $data['discount'] = $discount['discount']?$discount['discount']:0;
            if ($msg) {
                Db::rollback();
            } else {
                Db::commit();
            }
        } catch (Exception $e) {
            Db::rollback();

        }
        return [$msg, $data];
    }

    /**
     * 下单
     * @Author: rocky
     * 2019/9/30 17:41
     * @param $post 提交校验数据
     * @return array|mixed|string
     * @throws \Exception
     */
    public static function place($post)
    {
        list($msg, $datas) = self::confim($post);
        if ($msg) {
            return $msg;
        } else {
            //是否免费洗衣
            $free_total_num = 0;
            if ($post['is_free_wish']){
                $carts = ShopCart::uid()->whereIn('id', $post['car_ids'])->select();
                foreach ($carts as $cart) {
                    $good_info = ShopGoods::where('id',$cart['good_id'])->find();
                    if ($good_info['cate_id'] != sysconf('free_cate')){
                        return "{$good_info['title']} 不参与免费洗衣";
                    }
                    $free_total_num += $cart['num'];
                }
            }
            $free_has_num = Token::freeNum($post['store_id']);
            if ($free_has_num < $free_total_num){
                return "免费次数不足";
            }
//          判断门店是否被禁用/下架
            $store = ShopStore::where('status',1)->find($post['store_id']);
             if (!$store) {
                 return '该门店不存在或已下架';
             }

            $uid = Token::id();
            $order_sn = Data::uniqidDateCode();
            $coupon_price = 0;
            $total_price = 0;
            $goods_price = 0;
            $buy_num = 0;

            $user_res = User::where('id',Token::id())->find();
            $discount = ShopMemberLevel::where('id',$user_res['lid'])->find();//折扣
            //统计金额
            $total_laundry = 0;//洗衣件数
            foreach ($datas['data'] as $key => $data) {
                $total_laundry+=$data['num'];
                 // 使用优惠券
                if ($post['coupon_id'] && $post['type'] == 6){
                    $price = $data['price'] * $data['num'] ;
                    $coupon = ShopCouponRecord::uid()->where('type',0)->find($post['coupon_id']);
                    if (!$coupon){
                        return '该优惠券已使用或已过期';
                    }else{
                        $coupon_info = ShopCoupon::with('store')->where('status',1)->get($coupon['coupon_id']);
                        if ($coupon_info['store_id'] > 0 && $coupon_info['store_id'] != $post['store_id']){
                            return "该优惠券指定{$coupon_info['store']['name']}使用";
                        }
                        if ($price >= $coupon_info['condition_price']){
                            $coupon_price += $coupon_info['cut_price'];
                        }
                    }
                }
                // $goods_price += $data['vip_price'] * $data['num'];
                // 强制换成会员价，需要做判断是否是会员
                // 判断订单的类型5=充值套餐，6=会员卡，1=预约 $post['type']==5 || $post['type']==6 || $post['type']==1 $user_res['lid'] == 0
                if($post['type']==1){
                    if($user_res['lid'] == 1 || $user_res['lid'] == 2 || $user_res['lid'] == 3 ){
                        $goods_price += $data['vip_price'] * $data['num'];
                    }else{
                        $goods_price += $data['price'] * $data['num'];
                    }
                }else{
                  $goods_price += $data['price'] * $data['num'];
                }
                
                // if($post['type']=="5" || $post['type']=="6"){
                //         $goods_price += $data['price'] * $data['num'];
                // }else{
                //     $goods_price += $data['vip_price'] * $data['num'];
                // }
                
                $buy_num += $data['num'];
            }
            //获取区域代理id
            $region_City = ShopSchoolRegion::where('id',$store['region_id'])->find();
            //商品标题
            $title = $datas['title'];
            //会员等级 折扣
            if ($discount && $post['type']!=5 && $post['type']!=6) {
                $goods_price *= ($discount['discount']/10);
            }
            //商品总价：商品结构+运费-优惠价
            $total_price = $goods_price + $post['freight_price'] - $coupon_price;
            //订单数据组装
            //判断type是否等于5或6（充值或会员卡订单，store_id = 0）
            if($post['type'] == 5 || $post['type'] == 6){
                $orderData = [
                    'title' => $title,
                    'type' => $post['type'],
                    'uid' => Token::id(),
                    'city_id' => $region_City['pid'],
                    'area_id' => $region_City['id'],
                    'store_id' => $post['store_id']?$post['store_id']:0,
                    'coupon_id' => $post['coupon_id']?$post['coupon_id']:0,
                    'subscribe_time' => $post['subscribe_time'],
                    'express_type' => 2,
                    'order_no' => $order_sn,
                    'discount_price' => $coupon_price,
                    'buy_num' => $buy_num,
                    'residue_num' =>  Token::laundryNum($post['store_id'])?Token::laundryNum($post['store_id']):0,
                    //'freight_price'=>$post['freight_price'],//运费
                    'goods_price' => $goods_price,
                    'total_price' => $total_price,
                    'pay_type' => $post['pay_type'],
                    'desc' => $post['desc'],
                    'is_discount' => $discount['discount']?1:0,
                    'discount' => $discount['discount'],
                    'latitude' => $post['latitude'],
                    'longitude' => $post['longitude'],
                    'name' => $post['name'],
                    'phone' => $post['phone'],
                    'user_address' => $post['user_address'],
                    'detailed_address' => $post['detailed_address'],
                    'address_door' => $post['address_door'],
                    'is_delivery' => $post['is_delivery']
                ];
            }else{
                $orderData = [
                    'title' => $title,
                    'type' => $post['type'],
                    'uid' => Token::id(),
                    'city_id' => $region_City['pid'],
                    'area_id' => $region_City['id'],
                    'store_id' => $post['store_id']?$post['store_id']:0,
                    'coupon_id' => $post['coupon_id']?$post['coupon_id']:0,
                    'subscribe_time' => $post['subscribe_time'],
                    'express_type' => 2,
                    'order_no' => $order_sn,
                    'discount_price' => $coupon_price,
                    'buy_num' => $buy_num,
                    'residue_num' =>  Token::laundryNum($post['store_id'])?Token::laundryNum($post['store_id']):0,
                    // 'residue_num' => (Token::laundryNum(0)?Token::laundryNum(0):0) - $total_laundry,
                    'freight_price'=>$post['freight_price'],//运费
                    'goods_price' => $goods_price,
                    'total_price' => $total_price,
                    'pay_type' => $post['pay_type'],
                    'desc' => $post['desc'],
                    'is_discount' => $discount['discount']?1:0,
                    'discount' => $discount['discount'],
                    'latitude' => $post['latitude'],
                    'longitude' => $post['longitude'],
                    'name' => $post['name'],
                    'phone' => $post['phone'],
                    'user_address' => $post['user_address'],
                    'detailed_address' => $post['detailed_address'],
                    'address_door' => $post['address_door'],
                    'is_delivery' => $post['is_delivery']
                ];
            }

            
            Db::startTrans();
            try {
                //删除购物车
                if ($post['type'] == 1) {
                    ShopCart::uid()->whereIn('id', $post['car_ids'])->delete();
                }
                //购买会员卡使用优惠券
                if ($post['coupon_id'] && $post['type'] == 6){
                    ShopCouponRecord::uid()->where('id',$post['coupon_id'])->setField('type',1);
                }
                $user_order = ShopOrder::uid()->where('store_id',$post['store_id'])->field('id')->find();
                if (!$user_order){
                    User::where('id',$uid)->setField('store_id',$post['store_id']);
                }
                $original_store_id = User::where('id',Token::id())->value('original_store_id');
                if (!$original_store_id){
                    User::where('id',$uid)->setField('original_store_id',$post['store_id']);
                }
                $user_res = User::where('id',Token::id())->find();
                $data['has_subscribe'] = $user_res['is_record']?true:false;
                $order = ShopOrder::create($orderData);
                $orderGoods = [];

                //退款，判断是否是会员,进行会员价判断
                if($order['type'] == 5 || $order['type'] == 6){
                    foreach ($datas['data'] as $data) {
                        //快照组装
                        $orderGoods[] = [
                            'order_id' => $order['id'],
                            'card_id' => $data['card_id'],
                            'recharge_id' => $data['recharge_id'],
                            'good_id' => $data['good_id'],
                            'good_title' => $data['title'],
                            'good_logo' => $data['logo'],
                            'price' => $data['price'],
                            'num' => $data['num'],
                        ];
                    }
                }else{
                    if($user_res['lid'] > 0){
                        if($order['pay_type']==4){
                            foreach ($datas['data'] as $data) {
                                //快照组装
                                $orderGoods[] = [
                                    'order_id' => $order['id'],
                                    'card_id' => $data['card_id'],
                                    'recharge_id' => $data['recharge_id'],
                                    'good_id' => $data['good_id'],
                                    'good_title' => $data['title'],
                                    'good_logo' => $data['logo'],
                                    'price' => 0.00,
                                    'num' => $data['num'],
                                ];
                            }
                        }else{
                            foreach ($datas['data'] as $data) {
                                //快照组装
                                $orderGoods[] = [
                                    'order_id' => $order['id'],
                                    'card_id' => $data['card_id'],
                                    'recharge_id' => $data['recharge_id'],
                                    'good_id' => $data['good_id'],
                                    'good_title' => $data['title'],
                                    'good_logo' => $data['logo'],
                                    'price' => $data['vip_price'],
                                    'num' => $data['num'],
                                ];
                            }   
                        }
                    }else{
                        foreach ($datas['data'] as $data) {
                            //快照组装
                            $orderGoods[] = [
                                'order_id' => $order['id'],
                                'card_id' => $data['card_id'],
                                'recharge_id' => $data['recharge_id'],
                                'good_id' => $data['good_id'],
                                'good_title' => $data['title'],
                                'good_logo' => $data['logo'],
                                'price' => $data['price'],
                                'num' => $data['num'],
                            ];
                        }
                    }
                }
            
                (new ShopOrderGoods)->saveAll($orderGoods);
                 if ($post['type'] == 1){
                    if ($post['pay_type'] == 4){
                        $member = Token::member($post['store_id']);
                        if ($member[0]) {
                            $member_list = Token::memberId($post['store_id']);
                            if ($member_list[0]) {
                                if ($post['is_free_wish']){
                                    ShopMember::where('id', $member_list[1])->setInc('free_use_num', $buy_num);
                                }else{
                                    ShopMember::where('id', $member_list[1])->setInc('use_num', $buy_num);
                                }
                                $residue_num = Token::laundryNum($post['store_id'])?Token::laundryNum($post['store_id']):0;
                                $update_data = [
                                    'total_price' => 0,
                                    'status' => 2,
                                    // 'status' => 8,//已经付款，但是店家未接单
                                    'is_pay' => 1,
                                    'pay_type' => 4,
                                    'residue_num' => $residue_num
                                ];
                                ShopOrder::where('id', $order['id'])->update($update_data);
                                Account::record('0.00', $order['uid'],"{$order['title']}",1,0,"会员卡支付 - 订单号：{$order['order_no']}",$order['store_id'],$order['id']);
                            }
                            $is_free = true;
                        }
                    }else{
                        $is_free = false;
                    }
                }else{
                    $is_free = false;
                }
                Db::commit();
                return [
                    'order_id' => $order['id'],
                    'total_price' => $total_price,
                    'is_free' => $is_free
                ];
            } catch (Exception $e) {
                Db::rollback();
                return $e->getMessage();
            }
        }
    }

    /**
     * 删除关闭订单
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/12/13 10:56
     * @return int
     */
    public static function del()
    {
        return ShopOrder::where('status', -1)->whereTime('create_at', '<=', time() - sysconf('order_cancel_del_time') * 60 * 60)->setField('is_deleted', 1);
    }

    /**
     * 会员自动过期
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/12/13 10:56
     * @return int
     */
    public static function card()
    {
        $data = [
            'total_num' => 0,
            'use_num' => 0,
            'status' => 0
        ];
        return ShopMember::whereTime('expire_time', '<', time())->update($data);
    }
    
    /**
     * 确认收货
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/12/13 10:56
     * @return int
     */
    public static function confirm()
    {
        return ShopOrder::where('status', 3)->whereTime('delivery_time', '<=', time() - sysconf('order_confirm_time') * 60 * 60 * 24)->setField('status', 4);
    }
}